<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { message, Cascader } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import { doSizeGroupInfo, doSizeGroupAdd, doSizeGroupEdit } from '#/api/sizeGroup'
import { getCategoryTree } from '#/api/goodsCategory'
import { useVbenForm } from '#/adapter/form'

const { SHOW_CHILD } = Cascader;

const sizeGroupId = ref<Number>()
const formData = ref<any>({})
const title = ref('新增尺码组')
const emit = defineEmits(['fetch-data'])
const data = ref<any>()

/**
 * 初始化清空
 */
const initClear = async () => {
  sizeGroupId.value = 0
  formData.value = {}
}

/**
 * 获取品类树数据
 */
const fetchCategoryOptions = async () => {
  try {
    const response = await getCategoryTree()
    const categoryOptions = response || []
    
    // console.log('categoryOptions', response)
    // 动态更新 formApi 中的 category_id 选项
    if (formApi) {
      formApi.updateSchema([
        {
          componentProps: {
            options: categoryOptions,
          },
          fieldName: 'category_id',
        },
      ])
    }
  } catch (error) {
    console.error('获取品类树失败:', error)
  }
}

/**
 * 初始化
 */
const init = async () => {
  // 获取品类树
  // await fetchCategoryOptions()
}

/**
 * 获取数据
 */
const fetchData = async () => {
  if (sizeGroupId.value) {
    let { row } = await doSizeGroupInfo({ id: sizeGroupId.value })
    formApi.setValues(row)
    formData.value = row
  }
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入尺码组名称',
      },
      fieldName: 'name',
      label: '尺码组名称',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      fieldName: 'cate_tag',
      label: '品类范围',
      defaultValue: '0',
      componentProps: {
        options: [
          { label: '全部品类', value: '0' },
          { label: '指定品类', value: '1' },
        ],
      },
    },
    {
      component: 'Cascader',
      fieldName: 'category_id',
      label: '指定品类',
      dependencies: {
        triggerFields: ['cate_tag'],
        if(values) {
          return values.cate_tag === '1'
        },
      },
      componentProps: {
        options: [],
        multiple: true,
        placeholder: '请选择品类',
        showSearch: true,
        allowClear: true,
        showCheckedStrategy: SHOW_CHILD,
        // maxTagCount: 'responsive',
        fieldNames: {
          label: 'label',
          value: 'value',
          children: 'children',
        },
      },
    },
  ],
  handleSubmit: async (value) => {
    const { valid } = await formApi.validate()
    if (valid) {
      try {
        modalApi.lock()
        if (sizeGroupId.value) {
          await doSizeGroupEdit({ ...value, id: sizeGroupId.value })
          message.success('编辑成功')
        } else {
          await doSizeGroupAdd(value)
          message.success('添加成功')
        }
        emit('fetch-data')
        modalApi.close()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        modalApi.unlock()
      }
    }
  },
  handleReset: () => {
    modalApi.close()
  },
  showDefaultActions: false,
})

const [Modal, modalApi] = useVbenModal({
  class: 'w-1/2 h-[600px]',
  destroyOnClose: true,
  onOpened() {
     fetchCategoryOptions()
  },
  onOpenChange: (isOpen: boolean) => {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>()
      title.value = data.value?.info?.id ? '编辑尺码组' : '新增尺码组'

      if (data.value?.info?.id) {
        sizeGroupId.value = data.value.info.id
      }

      init()
      fetchData()
    }
  },
  onCancel: () => {
    modalApi.close()
  },
  onConfirm: () => {
    formApi.submitForm()
  },
})
</script>

<template>
  <Modal :title="title">
    <Form />
  </Modal>
</template>

